import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
// 导入服务
import { StorageService } from '../../services/storage.service';
@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
  public search:any = '';
  public searchList:any[] = [];
  public keyword:string = '';
  public todoList = [];
  //  获取到子组件的实例 可以调用子组件的属性和方法
  @ViewChild('mynews', {read: true, static: false}) mynews:ElementRef
  // 使用服务
  constructor(public storage:StorageService) {

  }
  add() {
    if (this.searchList.indexOf(this.search) === -1) {
      this.searchList.push(this.search);
      this.storage.set('search', this.searchList);
    } else {
      window.alert('数据已经存在');
    }
    this.search = '';
  }
  delete(i){
    this.searchList.splice(i, 1);
    this.storage.set('search', this.searchList);
  }
  addItem() {
    if (!this.ishas(this.todoList, this.keyword)){
      this.todoList.push({
        title: this.keyword,
        flag: false,
      });
      this.storage.set('todolist', this.todoList);
    }
  }
  public ishas(todoList:any[],title:any):boolean{
    for (let i = 0; i < this.todoList.length; i++) {
      if (todoList[i].title === title) {
        return true;
      }
    }
    return false;
  }
  public deleteItem(i){
    this.todoList.splice(i,1)
    this.storage.set('todolist', this.todoList);
  }
  ngOnInit() {
    this.searchList = this.storage.get('search') || [];
    this.todoList = this.storage.get('todolist') || [];
  }
  checkboxChange(){
    this.storage.set('todolist', this.todoList);
  }
  ngAfterViewInit(): void {
    //  调用子组件的方法和属性
    //  强制断言 可以修改一些错误
    console.log((this.mynews as any).username);
    console.log((this.mynews as any).getUsername());
  }
}
